package com.maimao.email;

import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @author MaoLin Wang
 * @date 2021/3/26 5:42 下午
 */
@Component
@Slf4j
public class EmailSender {
    @Autowired
    private JavaMailSenderImpl javaMailSender;

    private static final String SUBJECT_PREFIX = "麦猫商城——";

    @Value("${spring.mail.username}")
    private String from;

    /**
     * 发送邮件 系统发送
     *
     * @param subject 主题
     * @param target  目标邮件
     * @param content 内容
     */
    public void send(String subject, String target, String content) {
        SimpleMailMessage message = new SimpleMailMessage();
        //标题
        message.setSubject(SUBJECT_PREFIX + subject);
        message.setText(content);
        message.setSentDate(new Date());
        //发送人
        message.setFrom(from);
        //收件人
        message.setTo(target);

        javaMailSender.send(message);
    }

    /**
     * 发送html
     *
     * @param subject
     * @param target
     * @param html
     */
    public void sendHtml(String subject, String target, String html) {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        try {
            //标题
            mimeMessage.setSubject(SUBJECT_PREFIX + subject);

            mimeMessage.setSentDate(new Date());

            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "utf-8");
            //发送人
            helper.setFrom(from, "麦猫商城");
            //收件人
            helper.setTo(target);
            helper.setText(html, true);
            javaMailSender.send(mimeMessage);
            log.info("发送邮件成功{}",mimeMessage.toString());


        } catch (MessagingException | UnsupportedEncodingException e) {
            e.printStackTrace();
            log.error("发送邮件失败：{}", mimeMessage.toString());
        }


    }


}
